<template>
  <el-dialog :title="title" :visible.sync="open" width="750px"  :show-close="close" :before-close="cancel">
    <div v-loading="loading">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="章节名称" prop="name">
              <el-input style="width: 218px" v-model="form.name" placeholder="请输入章节名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseId">
              <el-select filterable v-model="form.courseId" placeholder="请选择课程" @change="getCataloguePidDict">
                <el-option v-for="(item,index) in courseDictList" :key="index" :label="item.name"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="章节类型" prop="type">
              <el-select filterable v-model="form.type" placeholder="请选择章节类型">
                <el-option v-for="(item,index) in catalogueTypeList" :key="item.id" :label="item.name"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属章" prop="pid">
              <el-select filterable v-model="form.pid" placeholder="请选择售卖方式">
                <el-option v-for="(item,index) in parentList" :key="index" :label="item.name"
                           :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="章节排序" prop="name">
              <el-input-number  style="width: 218px" v-model="form.index" controls-position="right" :min=1 :max=100></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="视频封面" prop="coverUrl">
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              action="http://localhost/dev-api/xingyue/upload/img"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleImgSuccess"
              :before-upload="beforeImgUpload"
            >
              <img v-if="form.coverUrl" :src="form.coverUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
          <el-col :span="4">
            <el-form-item label="上传视频" prop="mediaUrl">
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-upload
              class="avatar-uploader"
              action="http://localhost/dev-api/xingyue/upload/video"
              :headers="upload.headers"
              :show-file-list="false"
              :on-progress="uploadVideoProcess"
              :on-success="handleVideoSuccess"
              :before-upload="beforeVideoUpload"
            >
              <video v-if="mediaUrl !=''"
                     :src="mediaUrl"
                     class="avatar"
                     controls="controls">
                您的浏览器不支持视频播放
              </video>
              <i v-else-if="mediaUrl =='' && !videoFlag"
                 class="el-icon-plus avatar-uploader-icon"></i>
              <el-progress v-if="videoFlag == true"
                           type="circle"
                           :percentage="videoUploadPercent"
                           style="margin-top:7px;"
              ></el-progress>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>
      <div style="display: flex;justify-content: center;margin-top: 40px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </el-dialog>

</template>
<script>

import { courseDict } from '@/api/xingyue/course'
import { cataloguePidDict,insertCatalogue } from '@/api/xingyue/catalogue'
import { getToken } from '@/utils/auth'

export default {

  emits: ['refresh'],
  data() {
    return {
      //是否显示进度条
      videoFlag: false,
      //进度条的进度，
      videoUploadPercent: "",
      //   控制开关
      open: false,
      // 显示关闭
      close:true,
      // loading
      loading: false,
      // 视频地址
      mediaUrl: '',
      // 显示框标题
      title: '新增章节',
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() }
      },
      //   表格参数
      form: {
        coverUrl:undefined,
        mediaId:undefined,
        name: undefined,
        courseId: undefined,
        type: undefined,
        pid: undefined,
        index: undefined
      },
      //   课程字典集合
      courseDictList: [],
      //   目录类型集合
      catalogueTypeList: [
        { id: 1, name: '章' },
        { id: 2, name: '节' },
        { id: 3, name: '测试' }
      ],
      //   父章节集合
      parentList: []
    }
  },
  computed: {},
  mounted() {

  },
  methods: {
    /** 初始化方法*/
    async init() {
      this.open = true
      this.loading = true
      await this.getCourseDict()
      this.loading = false
    },
    /** 课程字典*/
    getCourseDict() {
      courseDict().then(response => {
        if (response.code == 200) {
          this.courseDictList = response.data
        }
      })
    },
    /** 获得父章节*/
    getCataloguePidDict() {
      cataloguePidDict(this.form.courseId).then(response => {
        if (response.code == 200) {
          this.parentList = response.data
        }
      })
    },
    /** 图片上传*/
    handleImgSuccess(response) {
      if (response.code == 200) {
        this.$set(this.form, 'coverUrl', response.data)
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    /** 视频上传*/
    handleVideoSuccess(response) {
      if (response.code == 200) {
        this.mediaUrl = response.data.path
        this.form.mediaId = response.data.id
        this.videoUploadPercent = 0;
        this.videoFlag = false
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    /** 视频进度条*/
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    /** 图片上传之前的校验*/
    beforeImgUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /** 视频上传之前的校验*/
    beforeVideoUpload(file) {
      const isMp4 = file.type === 'video/mp4'
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isMp4) {
        this.$message.error('上传视频只能是 Mp4 格式!')
      }
      if (!isLt50M) {
        this.$message.error('上传图片大小不能超过 50MB!')
      }
      return isMp4 && isLt50M
    },
    /** 传递刷新方法*/
    refreshData(){
      this.open = false;
      this.$emit("refresh")
    },
    /** 确定提交*/
    submitForm(){
      console.log(this.form)
      insertCatalogue(this.form).then(response=>{
        if (response.code==200) {
          this.$message.success('新增成功')
          this.refreshData()
          this.form={}
        } else {
          this.$message.error('新增失败')
        }
      })
    },
    /** 取消*/
    cancel(){
      this.open = false;
      this.form={}
    }
  }
}
</script>

<style scoped="scoped">

.avatar-uploader .el-upload {
  border: 5px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  padding-top: 80px;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
